<?php

namespace app\admin\controller\facrm\apps;

use app\admin\model\AuthGroup;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 开放应用
 * @icon fa fa-tags
 */
class Apps extends Backend
{

    protected $model = null;
    protected $noNeedRight = ['selectpage'];
    protected $key = "apps_setting_lists";
    protected $addon_config = array();

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\facrm\Setting();
        $this->addon_config = get_addon_config('facrm');
        $this->view->assign("sourceList", $this->addon_config['source']);
        $this->request->filter(['strip_tags']);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);
        $this->groupList = $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        Tree::instance()->init($groupList);
        if ($this->auth->isSuperAdmin()) {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v) {
                $groupdata[$v['id']] = $v['name'];
            }
        } else {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n) {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v) {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }
        $groupdata[0] = '选择归属组';
        $this->view->assign('groupdata', $groupdata);

    }

    /**
     * 查看列表
     * @return string|\think\response\Json
     * @throws \think\Exception
     */
    public function index()
    {

        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->where('key', $this->key)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $total = $this->model
                ->where($where)
                ->where('key', $this->key)
                ->order($sort, $order)
                ->count();

            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加应用
     * @return mixed
     */
    public function add()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if (empty($params['values'])) $this->error(—);
            $this->request->post(['row' => array_merge($params, [
                'values' => json_encode($params['values'])
            ])]);
        }
        $this->view->assign('key', $this->key);
        return parent::add();
    }

    /**
     * 修改应用
     * @return mixed
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if (empty($params['values'])) $this->error();
            $this->request->post(['row' => array_merge($params, [
                'values' => json_encode($params['values'])
            ])]);
        }
        $this->view->assign('key', $this->key);
        $this->view->assign('key', $this->key);
        return parent::edit($ids);
    }

    /**
     * 同步fa用户配置
     */
    public function synFaUserSet()
    {

        $this->key = "syn_fa_user";
        $row = $this->model->detail($this->key);
        if ($this->request->isPost()) {
			if (!$this->auth->isSuperAdmin()) {
                $this->error(__('超级管理员才能编辑'));
            }
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params = array_merge($params, [
                        'values' => json_encode($params['values'])
                    ]);
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    if (!$row) {
                        $result = $this->model->allowField(true)->save($params);
                    } else {
                        $result = $row->allowField(true)->save($params);
                    }

                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        };
        if (!$row) {
            //不存在就设置一些默认数据
            $row['values'] = "{\"source\":\"0\",\"group_id\":\"0\",\"owner_user_id\":\"\",\"needfollow\":\"0\",\"status\":\"0\"}";
        }
        $this->view->assign("row", $row);
        $this->view->assign('key', $this->key);
        return $this->view->fetch();

    }

    /**
     * 企业微信配置
     */
    public function workweixin()
    {
        $this->key = "work_weixin_set";
        $row = $this->model->detail($this->key);

        if ($this->request->isPost()) {
            if (!$this->auth->isSuperAdmin()) {
                $this->error(__('超级管理员才能编辑'));
            }
                $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params = array_merge($params, [
                        'values' => json_encode($params['values'])
                    ]);
                    if (!$row) {
                        $result = $this->model->allowField(true)->save($params);
                    } else {
                        $result = $row->allowField(true)->save($params);
                    }

                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();
        foreach ($groupList as $k => $v) {
            $groupName[$v['id']] = $v['name'];
        }

        if (!$row) {
            //不存在就设置一些默认数据
            $row['values'] = "{\"corp_id\":\"\",\"contacts_secret\":\"\",\"customer_secret\":\"\",\"customer_callback\":\"\",\"customer_callback_token\":\"\",\"EncodongAESKey\":\"\",\"agent_id\":\"\",\"agent_secret\":\"\",\"source\":\"0\",\"group_id\":\"0\"}";
        }

        $this->view->assign('groupdata', $groupName);
        $this->view->assign("row", $row);


        $this->view->assign('key', $this->key);
        return $this->view->fetch();
    }

}
